﻿using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Asn1.Mozilla;
using Repository.Models;
using Repository.Service;
using System.Security.Claims;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authorization;
using AutoMapper;
using Repository.Dtos;

namespace Controller.Controllers {
	[ApiController]
	[Route("[controller]")]
	public class SurveyController : ControllerBase {
		private readonly SurveyService _surveyService;
		private readonly IMapper _mapper;
		public SurveyController(SurveyService surveyService, IMapper mapper) {
			_surveyService = surveyService;
			_mapper = mapper;
		}


		/// <summary>
		/// 分页获取问卷,uid为可选参数，使用uid可以查询个人问卷
		/// </summary>
		/// <param name="uid"></param>
		/// <param name="pageIndex"></param>
		/// <param name="pageSize"></param>
		/// <returns></returns>
		[HttpGet]
		[Authorize]

		public ActionResult GetSurvey(Guid? uid, int pageIndex, int pageSize) {
			try {
				var surveys = uid.HasValue ? _surveyService.GetSurveysOfUser(uid.Value, pageIndex, pageSize).Result
					: _surveyService.GetSurveysWithPage(pageIndex, pageSize).Result;
				return Ok(_mapper.Map<List<Survey>, List<SurveyShowDto>>(surveys));
			}
			catch (Exception ex) {
				return BadRequest(ex.Message);
			}
		}

		/// <summary>
		/// 通过Id获取问卷信息(不含内容)
		/// </summary>
		[HttpGet("One/")]
		[Authorize]
		public ActionResult SearchById(Guid Id) {
			try {
				var survey = _surveyService.GetConcreteSurvey(Id).Result;
				return Ok(new {
					survey.Id,
					survey.Description,
					survey.FillNumer,
					survey.State,
					survey.CreatedTime
				});
			}
			catch (Exception ex) {
				Console.WriteLine(ex.Message);
				return BadRequest(ex.Message);
			}
		}

		/// <summary>
		/// 获取问卷内容
		/// </summary>
		/// <param name="Id"></param>
		/// <returns></returns>
		[HttpGet("Detail/")]
		[Authorize]

		public ActionResult GetConcreteSurvey(Guid Id) {
			try {

				var result = _surveyService.GetConcreteSurvey(Id).Result;
				//var fdto = result.
				var Questions =
					result.Questions.Select(q => new {
						q.Id,
						QuestionType = q.Type,
						q.Index,
						Content = q.Description,
						Options = q.Choices.Select(c => new {
							//c.Id,
							c.Index,
							Value = c.Description,
						})
						.OrderBy(c => c.Index).ToList()
					}).OrderBy(q => q.Index).ToList()
				;

				return Ok(new {
					result.Id,
					result.Name,
					Title = result.Description,
					result.Reward,
					result.State,
					result.CreatedTime,
					Questions,
				});
			}
			catch (Exception ex) {
				Console.WriteLine(ex.Message);
				return BadRequest(ex.Message);
			}
		}

		[HttpPost("EditSurvey/")]
		[Authorize]

		public ActionResult EditSurvey(Guid Id, [FromBody] FrontEndSurveyDto frontSurvey) {
			try {
				var res = _surveyService.Delete(Id).Result;
				GetSurvey(frontSurvey);
			}
			catch (Exception ex) {
				return BadRequest(ex.Message);
			}
			return Ok("Edit Success");
		}

		[HttpPost("NewSurvey")]
		[Authorize]

		public ActionResult GetSurvey([FromBody] FrontEndSurveyDto frontSurvey) {
			var surveyBase = frontSurvey.ToCreateDto();
			var res1 = _surveyService.AddNewSurvey(_mapper.Map<Survey>(surveyBase)).Result;
			if (res1 == Guid.Empty)
				return BadRequest("Add Fail");
			var surveyQues = DtoExtensions.ToQuestionDto(frontSurvey.Questions);
			var res2 = _surveyService.AddQuestionsIntoSurvey(res1, surveyQues).Result;
			if (res2)
				return Ok("Add Success");
			return BadRequest("Add Fail");
		}

		///// <summary>
		///// 发布者添加新问卷的基本信息
		///// </summary>
		//[HttpPost("NewSurvey")]
		////[Authorize]
		//public ActionResult AddNewSurvey([FromBody] SurveyCreateDto surveyDto) {
		//	//var result = _surveyService.AddNewSurvey(surveyDto).Result;
		//	var result = _surveyService.AddNewSurvey(_mapper.Map<Survey>(surveyDto)).Result;
		//	if (result)
		//		return Ok("Add Success");
		//	return BadRequest("Add Failed");
		//}

		///// <summary>
		///// 添加问卷的问题
		///// </summary>
		//[HttpPost("NewQuestions")]
		//public ActionResult AddSurvey(Guid surveyId, [FromBody] List<QuestionDto> questionDtos) {
		//	var result = _surveyService.AddQuestionsIntoSurvey(surveyId, questionDtos).Result;
		//	if (result)
		//		return Ok("Add Success");
		//	return BadRequest("Add Failed");
		//}

		/// <summary>
		/// 填完问卷提交
		/// </summary>
		/// <param name="answers"></param>
		/// <returns></returns>
		[HttpPost("Submit")]
		[Authorize]
		public ActionResult SubmitSurvey([FromBody] AnswerDto answers) {
			var res = _surveyService.SubmitSurvey(answers).Result;
			if (res) {
				return Ok("提交成功");
			}
			return BadRequest("提交失败");
		}

		/// <summary>
		/// 获取问卷选择题数据
		/// </summary>
		/// <param name="surveyId"></param>
		/// <returns></returns>
		[HttpGet("ChoiceData")]
		[Authorize]

		public ActionResult<SurveyData> GetData(Guid surveyId) {
			var res = _surveyService.GetSurveyData(surveyId).Result;
			if (res is not null)
				return Ok(res);
			return BadRequest("Not Found The Survey in Database.");
		}

		/// <summary>
		/// 删除
		/// </summary>
		[HttpDelete]
		[Authorize]

		public ActionResult Delete(Guid Id) {
			var res = _surveyService.DeleteSurvey(Id).Result;
			if (!res)
				return BadRequest("Delete Fail");
			return Ok("Delete Success");
		}
	}
}
